{include file="public/header" /}



<div class="page">
    <div class="fixed-bar">
        <div class="item-title">
            <div class="subject">
                <h3>{$model ? '修改问题' : '新增问题'}</h3>
                <h5></h5>
            </div>
            {include file="public/admin_items" /}
        </div>
    </div>
    <div class="fixed-empty"></div>
    <form id="question_class_form" method="post" name="articleClassForm">
        <table class="ds-default-table">
            <tbody>
            <input type="hidden" name="question_id" value="{$model->id | default = 0}">

            <tr class="noborder">
                <td class="required w150"><label class="validation" style="width:200px" >{$Think.lang.question_index_category}:</label></td>
                <td class="vatop rowform" style="width: 90%" >
                    {if isset($model)}
                    <select style="width:200px;" name="gc_id1" id="gc_id1">
                        <option value="0" {$model.gc_id1 == 0 ? 'selected' : ''}>{$Think.lang.ds_please_choose}...</option>
                        {notempty name="class_list"}
                        {foreach name="class_list" item="v"}
                        <option {$model->gc_id1 == $v.gc_id ? 'selected' : ''}  value="{$v.gc_id}">{$v.gc_name}</option>
                        {/foreach}
                        {/notempty}
                    </select>
                    {else}
                    <select style="width:200px;" name="gc_id1" id="gc_id1">
                        <option value="0">{$Think.lang.ds_please_choose}...</option>
                        {notempty name="class_list"}
                        {foreach name="class_list" item="v"}
                        <option value="{$v.gc_id}">{$v.gc_name}</option>
                        {/foreach}
                        {/notempty}
                    </select>
                    {/if}
                    <select style="width:200px;" name="gc_id2" id="gc_id2">

                    </select>
                    <select style="width:200px;" name="gc_id3" id="gc_id3">

                    </select>

                </td>
                <td class="vatop tips"></td>
            </tr>

            <tr class="noborder">
                <td class="required"><label class="validation">问题分类:</label></td>
                <td class="vatop rowform"><textarea type="text" name="title" id="title" class="txt" is_add="{$model->title? 0 : 1}" style="height:60px;">{$model->title | default=''}</textarea></td>
                <td class="vatop tips"></td>
            </tr>
            <tr class="noborder">
                <td class="required"><label class="validation">新增选项:</label></td>
                <td class="vatop rowform">
                    <textarea type="text" rows="4" id="option" class="txt" style="height:60px;width:240px;"></textarea>
                    <input type="hidden" name="option" id="option-hidden" value="{$model->option_id | default = ''}">
                    <button id="add-option" type="button" class="btn btn-small layui-btn-danger">新增选项</button>
                </td>
                <td class="vatop tips"></td>
            </tr>
            <tr class="noborder">
                <td class="required"><label class="validation">适用说明:</label></td>
                <td class="vatop rowform">
                    <textarea type="text" rows="4" name="shiyongshuoming"   class="txt" style="height:60px;width:240px;">{$model->shiyongshuoming| default=''}</textarea>
                </td>
                <td class="vatop tips"></td>
            </tr>
            {notempty name="options"}
            {foreach $options as $key => $val}

            <tr class="noborder option_{$val.id} parent_id_{$val.parent_id}">
                <td class="required"></td>
                <td class="vatop rowform">
                    {for start="0" end="$val.lev" }
                    &nbsp;&nbsp;&nbsp;&nbsp;|__
                    {/for}
                    <span class="thisoption">{$val.content}</span> <button type="button" data-option="{$val.content}" data-id="{$val.id}" class="btn btn-small btn-red layui-btn-danger del-option">删除</button>
                    <button type="button" data-option="{$val.content}" onclick="updateOption($(this))" data-id="{$val.id}" class="btn btn-small layui-btn-danger">修改</button>
                    {if $val.lev == 0}
                    <button type="button" data-option="{$val.content}" data-lev="{$val.lev}" data-id="{$val.id}" onclick="addChild($(this))" class="btn btn-small layui-btn-danger">添加次级现象</button>
                    {/if}
                    {if $val.lev != 0}
                    <button type="button" data-option="{$val.content}" data-lev="{$val.lev}" data-parentid="{$val.parent_id}" data-id="{$val.id}" id="add-answer-{$val.id}" onclick="addAnswer($(this))" class="btn btn-small add-answer">添加原因</button>
                    {/if}
                    <input type="hidden" name="option_answer[{$val.id}]" id="option_answer_{$val.id}" value="{$val.answer_id}">
                    <input type="hidden" name="option_answer_del[]" id="option_answer_del_{$val.id}">
                </td>
                <td class="vatop tips"></td>
            </tr>

            {foreach $val->answers as $k => $v}
            <tr class="noborder answer_{$v.id} option_{$val.id} parent_id_{$val.parent_id}" ischild="1">
                <td class="required"></td>
                <td class="vatop rowform">
                    {for start="0" end="$val.lev" }
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;--
                    {/for}
                    <span class="ss content-text-{$v.id} zy">{$v->content}</span>&nbsp;&nbsp;<button type="button" data-content="{$v.content}" data-option-id="{$val.id}" data-id="{$v.id}" onclick="deleteAnswer($(this))" class="btn btn-small layui-btn-danger">删除</button>
                    <button type="button" data-content="{$v.method}" data-method="{$v.method}" data-id="{$v.id}" onclick="addMethod($(this))" class="btn btn-small">修改</button>
                    <div><br>{for start="0" end="$val.lev" }
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {/for}
                        <span class="mm method-text-{$v.id}">{$v.method}</span>

                    </div>
                </td>
                <td class="vatop tips"></td>
            </tr>
            {/foreach}

            {/foreach}
            {/notempty}

            </tbody>
            <tfoot>
            <tr class="tfoot">
                <td colspan="15" >
                    <input class="btn" id="btn" type="button" value="{$Think.lang.ds_submit}"/>
                </td>
            </tr>
            </tfoot>
        </table>
        <input type="hidden" name="del_all_answer" value="" id="del_all_answer">
        <input type="hidden" name="del_all_option" value="" id="del_all_option">
    </form>
</div>

<div  class="layui-layer layui-layer-page layui-layer-prompt" id="add-answer-textaret"  style="z-index: 19891018; top: 8%; left: 40%; display: none;">
    <div class="layui-layer-title" style="cursor: move;">原因管理</div>
    <div id="" class="layui-layer-content">
        <div class="layui-layer-title" style="background: white">添加原因:</div>
        <textarea class="layui-layer-input" id="answer-content" style="background: white"></textarea>
        <br>
        <div class="layui-layer-title" style="background: white">添加处理办法:</div>
        <textarea class="layui-layer-input" id="method-content" style="background: white"></textarea>
    </div>
    <span class="layui-layer-setwin">
            <a class="layui-layer-ico layui-layer-close layui-layer-close1" href="javascript:;"></a>
        </span>
    <div class="layui-layer-btn layui-layer-btn-">
        <button class="btn btn-small" style="margin-top:5px;" id="add-answer-zidi" data-that="" data-lev data-id="" data-parent="" onclick="addAnswerPost($(this))">确定</button>
        <button class="btn btn-small" style="display: none;margin-top:5px;" id="edit-answer-zidi" data-that="" data-lev data-id="" onclick="EditAnswerPost($(this))">确定</button>
        <a class="layui-layer-btn1">取消</a>
    </div>
</div>

<script>
    function ischild() {
        $('.add-answer').each(function () {
            var ischild = $(this).parent().parent().next().attr('ischild');
            if (ischild) {
                $(this).css('background', '#ccc');
                $(this).attr('disabled', true)
            } else {
                $(this).css('background', '');
                $(this).removeAttr('disabled')
            }
        })
        $('button').each(function () {
            if ($(this).text() == '添加原因') {
                var ischild = $(this).parent().parent().next().attr('ischild');
                if (ischild) {
                    $(this).css('background', '#ccc');
                    $(this).attr('disabled', true)
                }else {
                    $(this).css('background', '');
                    $(this).removeAttr('disabled')
                }
            }

        })
    }
    ischild()

    $('#btn').click(function () {
        if (!$('#title').val()) {
            layer.msg('请检查问题名称');
            return false;
        }
        if (!$('#gc_id3').val()) {
            layer.msg('请选择分类');
            return false;
        }
        $('#question_class_form').submit();
    })
    $('#title').blur(function () {
        if ($(this).attr('is_add') == 0) {
            return false;
        }
        if (!$(this).val()) {
            layer.msg('请输入问题名称')
            return false;
        }
        $.post('uniqueQuestion', {
            title: $(this).val()
        }, function (res) {
            if (res.code == 10000) {
                layer.msg(res.message);
                $(this).text('')
                $(this).val('')
                $('#btn').css('background', '#ccc');
                $('#btn').attr('disabled', 'true');
            } else {
                $('#btn').css('background', '');
                $('#btn').removeAttr('disabled');
            }
        }, 'json')
    })
    function EditAnswerPost(that) {
        var id = that.attr('data-id');
        var pass= $('#answer-content').val()
        var method = $('#method-content').val()
        if (!pass) {
            layer.msg('原因不能为空');
            return false;
        }
        if (!method) {
            layer.msg('处理方法不能为空');
            return false;
        }
        $.post('addMethod.html?id='+id, {
            content: pass,
            method: method
        }, function (res) {
            console.log(res)
            layer.msg(res.message)
            if (res.code == 10000) {
                console.log(213123);
                $('.content-text-'+id).text(res.data.content)
                $('.method-text-'+id).text(res.data.method)
            }
            layer.closeAll()
        }, 'json')
    }
    // TODO 添加或修改处理方法
    function addMethod(that) {
        $('#add-answer-zidi').hide();
        $('#edit-answer-zidi').show();
        var id = that.attr('data-id');
        var content = $('.content-text-'+id).text();
        var method = $('.method-text-'+id).text();

        $('#answer-content').val($('.content-text-'+id).text());
        $('#method-content').val(method)
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            offset: ['8%', '40%'],
            content: $('#add-answer-textaret')
        });
        $('#edit-answer-zidi').attr('data-id', id)
        $('#edit-answer-zidi').attr('data-that', $('#edit-answer-'+id))
    }
    // TODO 修改选项
    function updateOption(that) {
        var id = that.attr('data-id');
        var content = that.attr('data-option');
        var index = layer.prompt({title: '修改-'+content, formType: 2, value: content}, function(pass, index){
            layer.close(index);
            $.post('updateOption.html?id='+id, {
                content: pass
            }, function (res) {
                layer.msg(res.message);
                if (res.code == 10000) {
                    that.parent().children().eq(0).text(pass)
                }
            }, 'json')
            // layer.msg('添加选项“'+pass+'"成功')
        });
    }
    // TODO 点击新增下级
    function addChild(that) {
        var parentid = that.attr('data-id'); // 父级的id
        var lev = that.attr('data-lev'); // 父级的级别
        layer.prompt({title: '请输入次级现象', formType: 2}, function(pass, index){
            layer.close(index);;
            addOption(pass, parentid, parseInt(lev)+1)
            // layer.msg('添加选项“'+pass+'"成功')
        });
    }

    // TODO 增加答案
    function addAnswer(that) {
        $('#answer-content').val('');
        $('#method-content').val('');
        var parentid = that.attr('data-parentid')
        var id = that.attr('data-id');
        var lev = that.attr('data-lev')
        console.log(id);
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            offset: ['8%', '40%'],
            content: $('#add-answer-textaret')
        });
        $('#add-answer-zidi').show();
        $('#edit-answer-zidi').hide();
        $('#add-answer-zidi').attr('data-id', id)
        $('#add-answer-zidi').attr('data-lev', lev)
        $('#add-answer-zidi').attr('data-that', $('#add-answer-'+id))
        $('#add-answer-zidi').attr('data-parentid', parentid)
    }
    var isclose = false;
    function addAnswerPost(that)
    {

        var id = that.attr('data-id');
        var lev = that.attr('data-lev')
        var pass = $('#answer-content').val();
        var method = $('#method-content').val();
        var thoese = $('add-answer-'+id);
        var parentid = that.attr('data-parentid');
        if (!pass) {
            layer.msg('原因不能为空');
            return false;
        }
        if (!method) {
            layer.msg('处理方法不能为空');
            return false;
        }
        console.log('----');
        console.log(id)
        var rfalse = false;
        $('.ss').each(function () {
            console.log($(this).text())
            if ($(this).text() == pass) {
                rfalse = true;
                layer.msg('该原因已存在');
                return false;
            }
        })
        $('.mm').each(function () {
            console.log($(this).text())
            if ($(this).text() == method) {
                rfalse = true;
                layer.msg('该处理办法已存在');
                return false;
            }
        })
        if (rfalse) {
            layer.msg('该原因已存在')
            return false;
        }
        if (isclose) {
            layer.msg('点击过快，请稍后。。')
            return false;
        }
        isclose = true;
        $.post('addOptionAnswer?option_id='+id, {
            content: pass,
            method: method,
            delmethodid: $('#del_all_answer').val()
        }, function (res) {
            if (res.code != 10000) {
                layer.msg(res.message, {time:500}, function () {
                    // layer.closeAll()
                    isclose = false
                })
                return false;
            }
            var pas = '';
            for (i=0; i<lev; i++) {
                pas += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
            }
            pas += '--';
            console.log(res.data.id)
            var html = '<tr class="noborder answer_'+res.data.id+' option_'+id+' parent_id_'+parentid+'" ischild="1">\n' +
                '<td class="required"></td>'+
                '<td class="vatop rowform">\n' +
                '    '+pas+'<span class="ss content-text-'+res.data.id+' zy">'+pass+'</span> <button type="button" data-content="'+pass+'" data-option-id="'+id+'" data-id="'+res.data.id+'" onclick="deleteAnswer($(this))" class="btn btn-small layui-btn-danger">删除</button>\n' +
                '&nbsp;<button type="button" data-content="'+pass+'" data-method="'+res.data.method+'" data-id="'+res.data.id+'" onclick="addMethod($(this))" class="btn btn-small">修改</button>'+
                '<div><br>' +
                '   '+pas+'<span class="mm method-text-'+res.data.id+'">'+res.data.method+'</span>\n' +
                '\n' +
                '                    </div>'
            '</td>\n' +
            '</tr>';
            // console.log(html)
            $('#add-answer-'+id).parent().parent().after(html);
            var answer_ids = $('#option_answer_'+id).val();
            console.log(answer_ids);
            console.log('#option_answer_'+id);
            console.log(answer_ids+','+res.data.id);
            if (!answer_ids) {
                $('#add-answer-'+id).next().val(res.data.id);
            } else {
                $('#add-answer-'+id).next().val(answer_ids+','+res.data.id);
            }
            $('#add-answer-'+id).attr('disabled' , true)
            $('#add-answer-'+id).css('background', '#ccc');

            that.attr('data-id', '');
            that.attr('data-lev', '')
            $('#answer-content').val('');
            $('#method-content').val('');
            layer.msg(res.message, {time: 1000}, function () {
                layer.closeAll()
                isclose = false
            })

        });
        ischild()
    }

    // TODO 删除答案
    function deleteAnswer(that) {
        var id = that.attr('data-id');
        var option_id = that.attr('data-option-id');
        var index = layer.confirm('确定要删除"'+that.attr('data-content')+'"答案吗？', {
            btn: ['确定', '取消'],
            title: false,
        }, function () {
            $('.answer_'+id).remove();
            ischild()
            var del = $('#option_answer_del_'+option_id).val();
            $('#option_answer_del_'+option_id).val(del+','+id);
            $('#del_all_answer').val(del+','+id);
            var answer_id = $('#option_answer_'+option_id).val();
            if (!answer_id) {
                answer_id = '';
            }
            answer_id = answer_id.split(',');
            for (i in answer_id) {
                if (!answer_id[i]) {
                    answer_id.splice(i, 1); // 删除空元素
                }
                if (answer_id[i] == id) {
                    answer_id.splice(i, 1); // 删除删掉的答案id
                }
            }
            answer_id = answer_id.join(',');
            if (!answer_id) {
                $('#option_answer_'+option_id).prev().removeAttr('disabled')
                $('#option_answer_'+option_id).prev().removeClass('background')
                $('#option_answer_'+option_id).prev().css('background', '')
            }
            $('#option_answer_'+option_id).val(answer_id);
            layer.msg('删除成功', {time: 500}, function () {
                ischild()
                layer.close(index)
            })


        })
        ischild()
    }

    // TODO 点击添加选项
    $('#add-option').click(function () {
        var option = $('#option').val();
        addOption(option, 0, 0)
        ischild()
    })

    /**
     *  TODO 添加选项
     * @param option
     * @returns {boolean}
     */
    function addOption(option, parentid, lev) {
        if (!option) {
            layer.msg('选项不能为空');
            return false;
        }
        if (!parentid) parentid = 0;
        if (!lev) lev = 0;
        var isfalse = false;
        $('.thisoption').each(function () {
            if ($(this).text() == option) {
                isfalse = true;
            }
        })
        if (isfalse) {
            layer.msg('已存在该现象');
            return false;
        }
        $.post('addOption?parent_id='+parentid, {
            option: option,
            lev: lev,
            deloption: $('#del_all_option').val()
        }, function (res) {

            console.log(res);
            layer.msg(res.message);
            if (res.code == 10000) {
                var del = $('#del_all_option').val()
                console.log('--+'+del)
                del = del.split(',');
                for (i in del) {
                    if (del[i] == res.data.id) {
                        del.splice(i, 1)
                    }
                }
                del = del.join(',');
                console.log('--'+del)
                $('#del_all_option').val(del)
                var lev_html = '';
                if (lev > 0) {
                    for (i = 0; i < lev; i ++) {
                        lev_html += '&nbsp;&nbsp;&nbsp;&nbsp;|__';
                    }
                }
                var html = '<tr class="noborder option_'+res.data.id+' parent_id_'+parentid+'">\n' +
                    '<td class="required"></td>'+
                    '                <td class="vatop rowform">\n' +
                    ''+lev_html+'                    <span class="thisoption">'+option+'</span> <button type="button" data-option="'+option+'" data-id="'+res.data.id+'" onclick="deleteOption($(this))" class="btn btn-small btn-red layui-btn-danger del-option">删除</button>\n' +
                    '<button type="button" data-option="'+option+'" onclick="updateOption($(this))" data-id="'+res.data.id+'" class="btn btn-small layui-btn-danger">修改&nbsp;</button>';



                if (lev == 0) {
                    html += '&nbsp;<button type="button" data-option="'+option+'" data-lev="'+res.data.lev+'" data-id="'+res.data.id+'" onclick="addChild($(this))" class="btn btn-small layui-btn-danger ">添加次级现象</button>'

                    html += '&nbsp;<button type="button" data-option="'+option+'" data-lev="'+res.data.lev+'" data-id="'+res.data.id+'" id="add-answer-'+res.data.id+'" data-parentid="'+parentid+'" onclick="addAnswer($(this))" class="btn btn-small layui-btn-danger add-answer">添加原因</button>'
                }
                if (lev != 0) {
                    html += '&nbsp;<button type="button" data-option="'+option+'" data-lev="'+res.data.lev+'" data-id="'+res.data.id+'" id="add-answer-'+res.data.id+'" data-parentid="'+parentid+'" onclick="addAnswer($(this))" class="btn btn-small layui-btn-danger add-answer">添加原因</button>';
                }
                html += '<input type="hidden" name="option_answer['+res.data.id+']" id="option_answer_'+res.data.id+'}">\n' +
                    '<input type="hidden" name="option_answer_del[]" id="option_answer_del_'+res.data.id+'">'
                '                </td>\n' +
                '            </tr>';
                if (parentid != 0) {
                    $('.option_'+parentid).after(html);
                } else {
                    $('tbody').append(html);
                }

                $('#option').val('');
                var option_ids = $('#option-hidden').val();
                var option_arr = option_ids.split(',');
                option_arr.push(res.data.id);
                option_ids = option_arr.join(',');
                $('#option-hidden').val(option_ids);
            }
        }, 'json')
        ischild()
    }

    // TODO 删除选项
    function deleteOption(that)
    {
        var index = layer.confirm('确定要解除"'+that.attr('data-option')+'"处理办法吗', {
            btn: ['确定', '取消'],
            title: false,
        }, function () {
            var id = that.attr('data-id');
            $('.option_'+id).remove();
            $('.parent_id_'+id).remove();
            var option_ids = $('#option-hidden').val();
            var option_arr = option_ids.split(',');
            for (i in option_arr) {
                if (option_arr[i] == id) {
                    option_arr.splice(i,1)
                }
            }
            var option = option_arr.join(',');
            $('#option-hidden').val(option);
            $('#del_all_option').val($('#del_all_option').val()+','+id)
            layer.msg('删除成功');
            layer.close(index)
        });
        ischild()
    }

    function getGcId1(gc_id1, select_id)
    {
        var select_od = select_id;
        $.ajax({
            type : "GET",
            contentType: "application/json;charset=UTF-8",
            url : ADMINSITEURL+"/Question/getClass.html?gc_id=" + gc_id1,
            success : function(result) {
                result = JSON.parse( result );
                var html = '';
                for(var i=0;i<result.length;i++){
                    if (result[i].gc_id == select_id) {
                        html += '<option selected value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    } else {
                        html += '<option value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    }
                }
                $('#gc_id2').html(html)
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    function getGcId2(gc_id1, select_id)
    {
        $.ajax({
            type : "GET",
            contentType: "application/json;charset=UTF-8",
            url : ADMINSITEURL+"/Question/getClass.html?gc_id=" + gc_id1,
            success : function(result) {
                result = JSON.parse( result );
                var html = '';
                for(var i=0;i<result.length;i++){
                    if (result[i].gc_id == select_id) {
                        html += '<option selected value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    } else {
                        html += '<option value="'+ result[i].gc_id +'">'+ result[i].gc_name +'</option>'
                    }
                }
                $('#gc_id3').html(html)
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    // 获取下级分类
    $('#gc_id1').on('change',function () {
        var gc_id1 = $(this).val();
        getGcId1(gc_id1)
    })

    $('#gc_id2').on('change',function () {
        var gc_id2 = $(this).val();
        getGcId2(gc_id2)
    })


    $('.del-option').click(function () {
        deleteOption($(this));

    })
</script>
{if isset($model)}
<script>

    // 编辑初始化，处理分类选中的问题
    if ($('#gc_id1').val()) {
        var gc_id1 = '{$model->gc_id1}';
        var gc_id2 = '{$model->gc_id2}';
        var gc_id3 = '{$model->gc_id3}';
        getGcId1(gc_id1, gc_id2)
        getGcId2(gc_id2, gc_id3)
    }
</script>
{/if}
